package com.pace.ribbon.controller;

import com.alibaba.fastjson.JSON;
import com.pace.ribbon.annotation.FastLog;
import com.pace.ribbon.annotation.LoveForest;
import com.pace.ribbon.asyn.Asyn;
import com.pace.ribbon.asyn.service.HelloService;
import com.pace.ribbon.config.Myconfig;
import com.pace.ribbon.dto.R;
import com.pace.ribbon.event.OrderCreateEvent;
import com.pace.ribbon.event.SpringContextHolder;
import com.pace.ribbon.log.enums.OperationType;
import com.pace.ribbon.log.enums.OperationUnit;
import com.pace.ribbon.starter.client.UserClient;
import com.sl.util.HttpClientUtil;
import io.swagger.annotations.ApiOperation;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@RestController
public class HelloController {

    @Autowired
    private Environment env;

    @Autowired
    private Myconfig myconfig;

    @Autowired
    private Asyn asyn;

    @Autowired
    private UserClient userClient;

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Resource
    private OkHttpClient okHttpClient;

    @Autowired
    private HelloService helloService;

    @GetMapping(value = "sayHello")
    public String hello(String res) {
        String port = env.getProperty("server.port");
        Map<String, Object> map = new HashMap<>();
        map.put("port", port);
        map.put("data", res);
        map.put("switch", myconfig.getAllSwitch());
        map.put("my.config.name", myconfig.getName());
        map.put("my.config.value", myconfig.getValue());
        return "hello:" + map;
    }


    @GetMapping(value = "exception")
    public String exception(int num) {
        R r = new R();

        if (num > 0) {
            r.setData("100对" + num + "取模：" + 100 % num);
            return r.toString();
        }
        if (num == 0) {
            int i = 100 % num;
            r.setData("异常");
            return r.toString();
        }
        return r.toString();
    }

    @GetMapping(value = "say")
    public R say() {
        R r = new R();
        r.setCode(200);
        r.setData("say");
        r.setMsg("succeed");
        return r;
    }

    @GetMapping(value = "asyn")
    public String asyn() throws InterruptedException {

        Long t1 = System.currentTimeMillis();
        asyn.saveLog();
        Long t2 = System.currentTimeMillis();
        helloService.iAsyncSay();
        Long t3 = System.currentTimeMillis();

        System.out.println("iAsyncSay耗时：" + (t3 - t2));

        return "costs:" + (t2 - t1) + "ms";
    }


    @GetMapping(value = "demo")
    @LoveForest(key = "I", value = "hello-world")
    public String demo() {

        // 下单
        OrderCreateEvent orderCreateEvent = new OrderCreateEvent(UUID.randomUUID().toString() + ",订单来源：OMS");
        List<String> objects = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            objects.add(i + "");
        }
        helloService.dealData(objects);
        // ....
        // 下单成功
        System.out.println("下单成功之后，异步做一些简单处理");


        SpringContextHolder.getApplicationContext().publishEvent(orderCreateEvent);

        System.out.println("异步之后！");

        String url = "https://www.fastmock.site/mock/3ddb36ed19a06abb22b4c7660935eb99/forest/api/getGames";
        Map<String, String> params = new HashMap<>();
        String response2 = httpClientUtil.post(url, params);
        String response = post(url, params);
        System.out.println(response2);
        System.out.println(response);

        return userClient.getName();
    }


    @ApiOperation(value = "查询", notes = "根据用户ID查询用户名")
    @GetMapping(value = "selectUser")
    @FastLog(detail = "通过用户ID[{{userId}}]获取用户名", level = 3, operationUnit = OperationUnit.USER, operationType = OperationType.SELECT)
    public String selectUser(String userId) {

        return userClient.getName() + ",id=" + JSON.toJSONString(userId);
    }


    public String post(String url, Map<String, String> params) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

}
